package com.sun.services.roles.impls;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.commons.Constant;
import com.sun.commons.base.BaseService;
import com.sun.commons.base.R;
import com.sun.dto.users.PermissionDto;
import com.sun.dto.users.RoleDto;
import com.sun.dto.users.RoleSearchModel;
import com.sun.services.roles.RoleMapper;
import com.sun.services.roles.repository.RoleRepository;
import com.sun.services.roles.service.PermissionService;
import com.sun.services.roles.service.RoleService;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@AllArgsConstructor
public class RoleServiceImpl extends BaseService implements RoleService {
    private final RoleMapper mapper;
    private final RoleRepository repository;
    private final RedisTemplate<String, Object> redisTemplate;
    private final ObjectMapper objectMapper;
    private final PermissionService permissionService;


    @Override
    public R createRole(RoleDto dto) {
        return null;
    }

    @Override
    public R updateRole(RoleDto dto) {
        return null;
    }

    @Override
    public R deleteRole(Long id) {
        return null;
    }

    @Override
    public R refreshPermissionCache(Long id) {
        RoleDto dto = repository.findByRoleId(id);
        if (dto == null) {
            return R.fail("角色不存在");
        }
        String key = Constant.REDIS_ROLE_PERMISSION_KEY + dto.code();

        List<PermissionDto> permissions = permissionService.findAllByRoleId(id);
        try {
            redisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(permissions.stream().map(x -> {
                return x.controller() + ":" + x.method();
            }).toArray(String[]::new)));
        } catch (Exception e) {
            return R.fail("缓存失败");
        }
        return R.ok();
    }

    @Override
    public String[] getPermissionCache(String roleCode) {
        try {
            String key = Constant.REDIS_ROLE_PERMISSION_KEY + roleCode;
            Object value = redisTemplate.opsForValue().get(key);
            if (value != null) {
                return objectMapper.readValue(value.toString(), String[].class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<RoleDto> getList(RoleSearchModel model) {
        return List.of();
    }

    @Override
    public Page<RoleDto> getPage(RoleSearchModel model) {
        return null;
    }
}
